package com.moss.common.util;

import com.moss.common.constant.Constants;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.Instant;
import java.time.LocalDate;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;

@Component
public class IncrCounter {


    @Resource
    RedisCache redisCache;

    private static final String SAMPLE_KEY_PATTERN = "sample_no_counter_%s";
    private static final String CHECK_KEY_PATTERN = "check_batch_no_counter_%s";
    private static final int EXPIRE_DAY = 7; // 7 days
    private static final DateTimeFormatter DTF = DateTimeFormatter.ofPattern("yyyyMMddHHmm")
            .withZone(ZoneId.systemDefault());

    /**
     * 根据采样类型生成采样编号
     * @param type
     * @return
     */
    public synchronized String randomSampleNo(String type){
        String key = String.format(SAMPLE_KEY_PATTERN, LocalDate.now().format(DateTimeFormatter.BASIC_ISO_DATE));
        return Constants.SAMPLE_PREFIX.get(type) + DTF.format(Instant.now()) + incrNumber(key);
    }


    public synchronized String randomCheckBatchNo(){
        String key = String.format(CHECK_KEY_PATTERN, LocalDate.now().format(DateTimeFormatter.BASIC_ISO_DATE));
        return DTF.format(Instant.now()) + incrNumber(key);
    }


    private String incrNumber(String key){
        Long incr = redisCache.incr(key, EXPIRE_DAY);
        if (incr < 1000){
            return String.format("%03d", incr);
        }else {
            return String.valueOf(incr);
        }
    }
}
